<template>
  <div class="create-ads">
    <el-drawer v-model="drawerAbs" title="广告基本信息" size="55%" class="native-anchor-drawer" direction="rtl" @close="handleDrawerClose(false)">
      <div class="drawer-content">
        <div class="drawer-content-item">
          <el-form :model="form" label-width="140px" label-position="left" :rules="rules" ref="formRef">
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span style="font-size: 16px; font-weight: 600">推广身份</span>
                </div>
              </template>

              <el-form-item label="推广身份" class="awemeId">
                <el-radio-group v-model="chatterNumber">
                  <el-radio-button label="1">抖音号</el-radio-button>
                  <!-- <el-radio-button label="2">企业</el-radio-button> -->
                </el-radio-group>
                <div class="awemeId-desc" v-if="chatterNumber === '1'">
                  <img src="https://tos.mobgi.com/web/native-ad-guide/2023092204.png" alt="" />
                  <span>选择抖音号作为推广身份，即进行原生广告投放</span>
                  <span>计划将在广告审核通过后进行内容审核，内容审通过后，可获得更多流量</span>
                </div>
              </el-form-item>
              <el-form-item label="匹配方式">
                <el-radio-group v-model="matchingMode1">
                  <el-radio-button label="1">所有广告选择同一个抖音号</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="选择抖音号" style="width: 60%" prop="awemeId">
                <!-- <el-button type="primary" @click="handleDrawerClose(false)">选择抖音号</el-button> -->
                <el-select v-model="form.awemeId" placeholder="请选择抖音号" @change="handleChatterNumber">
                  <el-option v-for="(itm, idx) in chatterNumberList" :key="idx" :label="itm.awemeName" :value="itm.awemeId" />
                </el-select>
              </el-form-item>
              <el-form-item class="" label-width="0" v-if="form.awemeId">
                <!-- 表格 -->
                <el-table :data="accountList" style="width: 100%" border v-if="showAccountTable">
                  <el-table-column prop="name" label="账户" width="300">
                    <template #default="{ row }">
                      <div class="val">{{ row.name }}</div>
                      <div class="text-[#ccc] val">ID: {{ row.id }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="address" label="抖音号">
                    <template #default="{ row }">
                      <div class="val">{{ row.awemeName }}</div>
                      <div class="text-[#ccc] val">{{ row.awemeId }}</div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-card>
            <el-card class="box-card" v-if="props.microPromotionType === 'WECHAT_APP'">
              <template #header>
                <div class="card-header">
                  <span style="font-size: 16px; font-weight: 600">原生锚点</span>
                </div>
              </template>
              <el-form-item label="原生锚点类型">
                <el-radio-group v-model="nativeAnchorType">
                  <el-radio-button label="1">选择已有</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="匹配方式">
                <el-radio-group v-model="matchingMode2">
                  <el-radio-button label="1">每个账户选择一个原生锚点</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="选择原生锚点" style="width: 60%" prop="anchorId">
                <el-button type="primary">自动生成</el-button>
                <!-- <el-button type="primary" @click="openLinkSelect">选择锚点</el-button> -->
                <!-- <el-select v-model="form.anchorId" placeholder="请选择原生锚点" @change="handleAnchor">
                  <el-option v-for="(itm, idx) in anchorList" :key="idx" :label="itm.anchorName" :value="itm.anchorId" />
                </el-select> -->
              </el-form-item>
              <!-- 表格 -->
              <el-table :data="anchorPointList" style="width: 100%" border v-if="showAnchorTable">
                <el-table-column prop="name" label="账户" width="300">
                  <template #default="{ row }">
                    <div class="val">{{ row.name }}</div>
                    <div class="text-[#ccc] val">ID: {{ row.id }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="address" label="锚点">
                  <template #default="{ row }">
                    <div class="val">{{ row.anchorName }}</div>
                    <div class="text-cut text-[#ccc] val">{{ row.anchorId }}</div>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
            <el-card class="box-card" v-if="props.microPromotionType === 'BYTE_APP'">
              <template #header>
                <div class="card-header">
                  <span style="font-size: 16px; font-weight: 600">字节小程序链接</span>
                </div>
              </template>
              <el-tabs v-model="form.selectAccountId" @tab-change="handleSelectAccountIdChange" type="border-card">
                <el-tab-pane v-for="(accountItm, accountIdx) in accountDataLists" :key="accountIdx" :label="accountItm.name" :name="accountItm.id">
                  <el-form-item label="链接方式">
                    <el-radio-group v-model="linkWay">
                      <el-radio-button label="1">已有链接</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="链接来源">
                    <el-radio-group v-model="accountItm.linkSource" @change="handleLinkSource">
                      <el-radio-button label="1">选择已有</el-radio-button>
                      <el-radio-button label="2">自动生成</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                  <!-- <el-form-item label="链接匹配方式">
                    <el-radio-group v-model="linkMatching">
                      <el-radio-button label="1">每个账户分别使用一个链接</el-radio-button> -->
                  <!-- <el-radio-button label="1">每个项目分别使用一个链接</el-radio-button>
                    <el-radio-button label="2">每个广告分别使用一个链接</el-radio-button> -->
                  <!-- </el-radio-group>
                  </el-form-item> -->
                  <el-form-item label="选择链接" style="width: 60%" v-if="accountItm.linkSource == '1'">
                    <!-- <el-button type="primary">选择链接</el-button> -->
                    <el-select v-model="accountItm.linkId" placeholder="请选择链接" @change="handleLink(accountItm, accountIdx)" style="width: 100%">
                      <el-option v-for="(itm, idx) in linkedList" :key="idx" :label="itm.linkRemark" :value="itm.linkId" :title="itm.link">
                        <span class="option-content" style="display: inline-block; width: 400px; overflow: hidden; text-overflow: ellipsis">
                          {{ itm.linkRemark }}
                        </span>
                      </el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item label="推广链接" v-if="accountItm.linkSource == '2'" prop="startPath">
                    <el-input v-model="accountItm.startPath" placeholder="请输入推广链接" />
                  </el-form-item>
                  <el-form-item label="推广参数" v-if="accountItm.linkSource == '2'" prop="params">
                    <el-input v-model="accountItm.params" placeholder="请输入推广参数" />
                  </el-form-item>
                </el-tab-pane>
              </el-tabs>
              <!-- 表格 -->
              <el-table :data="accountLinkList" style="width: 100%" border v-if="showLinkTable">
                <el-table-column prop="name" label="账户" width="300">
                  <template #default="{ row }">
                    <div class="val">{{ row.name }}</div>
                    <div class="text-[#ccc] val">ID: {{ row.id }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="address" label="链接">
                  <template #default="{ row }">
                    <div class="val">{{ row.linkName }}</div>
                    <div class="text-cut text-[#ccc] val">{{ row.linkUrl }}</div>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span style="font-size: 16px; font-weight: 600">创意组件</span>
                </div>
              </template>
              <!-- <el-form-item label="附加创意组件">
                <el-radio-group v-model="form.promotion.promotionMaterials.anchorMaterialList[0].anchorType">
                  <el-radio-button label="APP_INTERNET_SERVICE">不启用</el-radio-button>
                  <el-radio-button label="1">启用</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="匹配方式">
                <el-radio-group v-model="form.promotion.promotionMaterials.anchorMaterialList[0].anchorType">
                  <el-radio-button label="APP_INTERNET_SERVICE">每个账户选择一个创意组件</el-radio-button>
                  <el-radio-button label="2">每个项目选择一个创意组件</el-radio-button>
                  <el-radio-button label="3">每个广告选择一个创意组件</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="选择创意组件">
                <el-button type="primary">选择创意组件</el-button>
              </el-form-item> -->
              <el-form-item label="行动号召" class="call-to-action">
                <el-input
                  v-model="callToActionButtonsItem"
                  placeholder="空格分隔,最多10个,每个标签不超过6个字"
                  @keydown.enter.native="handleAddCallToActionButton"
                >
                  <template #append>
                    <span @click="handleAddCallToActionButton" role="button" tabindex="0">添加（回车键）</span>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item class="call-to-action-text">
                <div class="tagged-added">
                  <div class="tagged-added-title">
                    <span>已添加标签</span>
                    <span style="color: #409eff; cursor: pointer; line-height: 40px" @click="emptiedCallToActionButton"> 清空 </span>
                  </div>
                  <div class="tagged-added-content">
                    <div class="tagged-added-content-item" v-for="(item, index) in form.callToActionButtons" :key="index">
                      <span style="width: 120px">
                        <i>{{ item }}</i>
                        <el-icon @click="handleDelCallToActionButton(index)"><Close /> </el-icon>
                      </span>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-card>

            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span style="font-size: 16px; font-weight: 600">产品信息</span>
                </div>
              </template>
              <el-form-item label="配置模式">
                <el-radio-group v-model="configurationMode">
                  <el-radio-button label="1">统一配置</el-radio-button>
                  <!-- <el-radio-button label="1">分账户配置</el-radio-button>
                  <el-radio-button label="2">分项目配置</el-radio-button> -->
                </el-radio-group>
              </el-form-item>
              <el-form-item label="产品名称" prop="titles">
                <el-input v-model="form.titles" placeholder="请输入广告名称" maxlength="20" show-word-limit />
              </el-form-item>

              <el-form-item label="产品主图" prop="tempImage" class="products-img">
                <div class="products-img-box" v-if="!imgType || imgType === 'online'">
                  <div class="products-img-item" v-for="(item, index) in selectedRows" :key="index">
                    <img :src="item.url" alt="" />
                    <el-icon @click="delImg(index)"><Close /> </el-icon>
                  </div>
                  <div class="add-img" @click="addMaterialLibrary()">
                    <span>+ 素材库({{ selectedRows.length }}/10)</span>
                  </div>
                </div>
                <div class="localbox" v-if="!imgType || imgType === 'local'">
                  <ImgUpload
                    v-model="uploadFile"
                    :accountId="appStore.accountId"
                    :advertiserId="advertiserId[0].id"
                    :image-height-limt="108"
                    :image-width-limt="108"
                    :is-show-tip="false"
                    :limit="10"
                  />
                </div>
              </el-form-item>
              <el-form-item label="产品卖点" class="call-to-action">
                <el-input v-model="sellingPointsItem" placeholder="空格分隔,最多10个,每个标签不超过9个字" @keydown.enter.native="addSellingPoints">
                  <template #append>
                    <span @click="addSellingPoints" role="button" tabindex="0">添加（回车键）</span>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item class="call-to-action-text">
                <div class="tagged-added">
                  <div class="tagged-added-title">
                    <span>已添加标签</span>
                    <span style="color: #409eff; cursor: pointer; line-height: 40px" @click="emptiedSellingPoints"> 清空 </span>
                  </div>
                  <div class="tagged-added-content">
                    <div class="tagged-added-content-item" v-for="(item, index) in form.sellingPoints" :key="index">
                      <span style="width: 160px">
                        <i>{{ item }}</i>
                        <el-icon @click="delSellingPoints(index)"><Close /> </el-icon>
                      </span>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-card>
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span style="font-size: 16px; font-weight: 600">广告设置</span>
                </div>
              </template>
              <!-- <el-form-item label="配置模式" class="awemeId">
                <el-radio-group v-model="form.awemeId">
                  <el-radio-button label="UNIVERSAL_SMART">统一配置</el-radio-button>
                  <el-radio-button label="1">分账户配置</el-radio-button>
                  <el-radio-button label="2">分项目配置</el-radio-button>
                </el-radio-group>
              </el-form-item> -->
              <el-form-item label="来源" prop="source">
                <el-input v-model="form.source" placeholder="请输入来源，来源限2-10个字" minlength="2" maxlength="10" show-word-limit />
              </el-form-item>
              <el-form-item label="广告评论" class="awemeId">
                <el-radio-group v-model="form.isCommentDisable">
                  <el-radio-button label="ON">启用</el-radio-button>
                  <el-radio-button label="OFF">不启用</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-card>
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span style="font-size: 16px; font-weight: 600">广告预算与出价</span>
                </div>
              </template>
              <!-- <el-form-item label="配置模式" class="awemeId">
                <el-radio-group v-model="form.awemeId">
                  <el-radio-button label="UNIVERSAL_SMART">统一配置</el-radio-button>
                  <el-radio-button label="1">分账户配置</el-radio-button>
                  <el-radio-button label="2">分项目配置</el-radio-button>
                </el-radio-group>
              </el-form-item> -->
              <el-form-item label="广告预算" prop="budget">
                <el-input v-model="form.budget" type="number" placeholder="请输入广告预算" :min="300" :max="9999999.99" />
              </el-form-item>
              <el-form-item label="广告出价" class="cpaBid">
                <el-input v-model="form.cpaBid" type="number" placeholder="请输入广告出价" :min="0.01" :max="333" />
              </el-form-item>
            </el-card>
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span style="font-size: 16px; font-weight: 600">广告名称</span>
                </div>
              </template>
              <el-form-item label="广告名称" class="awemeId" prop="name">
                <el-input v-model="form.name" placeholder="请输入广告名称" maxlength="50" show-word-limit />
                <div class="text-[12px] text-[#ccc] tips">目前仅支持<日期>-<花名>-<剧名>-<编号></div>
              </el-form-item>
              <!-- <el-form-item label="广告动态标号">
                <el-input v-model="form.awemeId" placeholder="请输入动态标号" />
              </el-form-item> -->
              <el-form-item label="广告默认状态" class="awemeId" prop="operation">
                <el-radio-group v-model="form.operation">
                  <el-radio-button label="DISABLE" value="DISABLE">暂停</el-radio-button>
                  <el-radio-button label="ENABLE" value="ENABLE">启用</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-card>
          </el-form>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDrawerClose(false)">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
  <MaterialLibrary
    :isMaterialLibrary="isMaterialLibrary"
    @update:isMaterialLibrary="updateIsMaterialLibrary"
    @selectedRows="getSelectedRows"
    :imageIds="form.imageIds"
    :width="108"
    :height="108"
    :userList="props.advertiserId"
    :selectAdvertiserId="selectAdvertiserId"
    fileType="image"
    :selected="selectedRows"
  />
  <!-- 锚点选择 -->
  <LinkSelect ref="linkSelectRef" :type="props.microPromotionType" :advertiserId="props.advertiserId" @getAppInfo="getUserInfo" />
</template>

<script setup lang="ts" name="CreateAds">
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { getImageList } from '@/api/advertisement/materialLibrary';

import { getIesAccountSearch, createProjectPromotion, getTitleList } from '@/api/advertising/createAds';
import { listNativeAnchor } from '@/api/advertisement/nativeAnchor';
import { queryToolsAssetLinkList } from '@/api/advertisement/byte';

const props = defineProps([
  'drawerAbs',
  'advertiserId',
  'projectId',
  'microPromotionType',
  'dramaName',
  'anchorMaterialList',
  'promotionData',
  'urlsData'
]); //projectId项目id，advertiserId账户id
import { useAppStore } from '@/store/modules/app';
const emit = defineEmits(['update:drawerAbs', 'strategyUrls']); //'promotion','urls',
const appStore = useAppStore();
const drawerAbs = ref(false);
const isMaterialLibrary = ref(false);
const chatterNumber = ref('1');
const matchingMode1 = ref('1');
const matchingMode2 = ref('1');
const nativeAnchorType = ref('1');
const linkWay = ref('1');
const linkSource = ref('1');
const linkMatching = ref('1');
const configurationMode = ref('1');
const selectAdvertiserId = ref(''); // 选中的账户id

const startPath = ref('');
const params = ref('');

const imgType = ref<'online' | 'local'>();

const showAccountTable = ref(false);
const showLinkTable = ref(false);
const showAnchorTable = ref(false);

const isWeChat = computed(() => {
  return props.microPromotionType === 'WECHAT_APP';
}); // 是否是微信小程序
const selectedRows = ref([]);

const uploadFile = ref([]);

const chatterNumberList = ref([]);
const anchorList = ref([]); // 抖音号列表
const linkedList = ref([]); // 链接列表
const linkurls = ref(''); // 链接
const temporaryAwemeId = ref(''); // 抖音号
const callToActionList = ref([]); // 行动号召列表
const sellingPointList = ref([]); // 产品卖点列表
const callToActionButtonsItem = ref('');
const sellingPointsItem = ref('');

const linkSelectRef = ref(null);

const accountList = ref([]);
const anchorPointList = ref([]); // 锚点列表
const accountLinkList = ref([]); // 链接列表
// 初始化函数
const initializeAccountList = () => {
  accountList.value = props.advertiserId.map((item) => {
    return {
      ...item,
      awemeId: '',
      awemeName: '',
      linkUrl: '',
      linkName: '',
      linkId: '',
      anchorId: '',
      anchorName: ''
    };
  });
};

const linkDataList = ref([]);

// const roleForm;
const initFormData: any = {
  accountId: appStore.accountId, //管家账号id
  advertiserId: props.advertiserId[0].id, //广告主id
  selectAccountId: props.advertiserId[0].id,
  projectId: '7513840912507437075', // 项目id
  name: '<日期>-<花名>-<剧名>-<编号>', // 广告名称
  // anchorType: '',
  // anchorId: '',
  linkId: '',
  linkUrl: '',
  linkName: '',
  anchorId: '',
  anchorName: '',
  callToActionButtons: [],
  titles: props.dramaName,
  imageIds: [],
  tempImage: [],
  selectedRows: [],
  sellingPoints: [],
  awemeId: '',
  anchorRelatedType: 'AUTO', //原生锚点启用开关，允许值:不启用 OFF（默认值），自动生成 AUTO，手动选择 SELECT
  source: '', //来源
  isCommentDisable: 'ON', //广告评论
  operation: 'ENABLE',
  startPath: '',
  params: '',
  budget: 300,
  cpaBid: 0.01,
  urls: [
    {
      url: '',
      advertiserId: ''
    }
  ] //字节链接
};
const data = reactive({
  form: { ...initFormData },
  accountDataLists: [
    {
      name: '',
      linkSource: '1',
      linkId: '',
      startPath: '',
      params: '',
      linkUrl: '',
      linkName: '',
      awemeId: '',
      awemeName: '',
      anchorId: '',
      anchorName: ''
    }
  ],
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    accountId: appStore.accountId,
    advertiserId: props.advertiserId[0].id, // 测试   props.advertiserId
    // advertiserId: undefined,
    instanceId: props.advertiserId[0].instanceId, //  小程序ID，  注意：小程序ID和项目ID的来源需要明确，是否是新建项目里面去拿的
    // instanceId: '', //  字节小程序资产ID，通过【工具】-【获取字节小程序/小游戏】获取
    assetId: undefined,
    assetName: undefined,
    params: {}
  },
  rules: {
    awemeId: [{ required: true, message: '请选择抖音号', trigger: 'change' }],
    // anchorId: [{ required: true, message: '请选择原生锚点', trigger: 'change' }],
    linkId: [{ required: true, message: '请选择链接', trigger: 'change' }],
    titles: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    source: [{ required: true, message: '请输入来源', trigger: 'blur' }],
    name: [{ required: true, message: '请输入广告名称', trigger: 'blur' }],
    // startPath: [{ required: true, message: '请输入推广链接', trigger: 'blur' }],
    // params: [{ required: true, message: '请输入推广参数', trigger: 'blur' }],
    tempImage: [{ required: true, message: '请选择产品主图', trigger: 'blur' }]
  }
});
const { form, queryParams, rules, accountDataLists } = toRefs(data);

const handleSelectAccountIdChange = (val) => {
  accountLinkList.value = accountDataLists.value.filter((item) => item.id == val);
  if (accountLinkList.value[0].linkSource === '1') {
    handleQueryToolsAssetLinkList(val);
  }
  showLinkTable.value = accountLinkList.value[0].linkUrl ? true : false;
};
/**
 * 切换字节链接来源方式
 */
const handleLinkSource = () => {
  accountLinkList.value.map((item) => {
    item.linkId = null;
    item.linkUrl = null;
    item.linkName = null;
  });
  accountList.value.map((item) => {
    item.linkId = null;
    item.linkUrl = null;
    item.linkName = null;
  });
  showLinkTable.value = false;
};

/**
 * 锚点选择
 */
const openLinkSelect = () => {
  linkSelectRef.value?.show();
};

const getUserInfo = (val) => {
  // accountList.value = val;
  anchorPointList.value = val;
  showAnchorTable.value = true;
};

onMounted(() => {
  drawerAbs.value = props.drawerAbs;
  handleGetIesAccountSearch(queryParams.value);
  handleListNativeAnchor();
  handleGetTitleList(2); //产品卖点
  handleGetTitleList(3); //行动号召
  if (props.microPromotionType === 'BYTE_APP') {
    handleQueryToolsAssetLinkList(props.advertiserId[0].id);
  }
});

watch(
  () => props.drawerAbs,
  (val) => {
    drawerAbs.value = val;
    // console.log(accountDataLists.value, 'accountDataLists888');
    
  }
);
// 获取title标签名字
const handleGetTitleList = async (type) => {
  const res = await getTitleList({ type: type });
  if (res.code == 200) {
    if (type == 2) {
      form.value.sellingPoints = res.rows.slice(0, 10).map((item) => item.name); //产品卖点
    } else if (type == 3) {
      form.value.callToActionButtons = res.rows.slice(0, 10).map((item) => item.name); //行动号召
    }
  }
};
//
const submit = async () => {
  await proxy.$refs['formRef'].validate(async (valid: boolean) => {
    if (valid) {
      if (imgType.value === 'online' && selectedRows.value.length == 0) {
        ElMessage({
          message: '请选择产品主图',
          type: 'error'
        });
        return;
      }
      if (imgType.value === 'local' && uploadFile.value.length == 0) {
        ElMessage({
          message: '请选择产品主图',
          type: 'error'
        });
        return;
      }
      if (form.value.sellingPoints.length == 0) {
        ElMessage({
          message: '请添加产品卖点标签',
          type: 'error'
        });
        return;
      }
      if (form.value.callToActionButtons.length == 0) {
        ElMessage({
          message: '请添加创意组件标签',
          type: 'error'
        });
        return;
      }
      // 如果accountLists.value里面的有linkSource==1的情况下，则linkId必填

      if (props.microPromotionType === 'BYTE_APP') {
        let isLinkId = accountDataLists.value.some((item) => item.linkSource == '1' && !item.linkId);
        if (isLinkId) {
          ElMessage({
            message: '请选择链接',
            type: 'error'
          });
          return;
        }
        // 如果accountLists.value里面的有linkSource==2的情况下，则startPath和params必填
        let isStartPath = accountDataLists.value.some((item) => item.linkSource == '2' && !item.startPath);
        if (isStartPath) {
          ElMessage({
            message: '请输入推广链接',
            type: 'error'
          });
          return;
        }
        let isParams = accountDataLists.value.some((item) => item.linkSource == '2' && !item.params);
        if (isParams) {
          ElMessage({
            message: '请输入推广参数',
            type: 'error'
          });
          return;
        }
      }
      // if (selectedRows.value.length == 0) {
      //   ElMessage({
      //     message: '请选择素材',
      //     type: 'error'
      //   });
      //   return;
      // }
      if (props.microPromotionType === 'WECHAT_APP') {
        let newAnchorMaterialList = anchorPointList.value.map((item, index) => {
          return {
            anchorType: item.anchorType,
            advertiserId: props.advertiserId[index].id,
            anchorId: item.anchorId,
            anchorName: item.anchorName,
            name: form.value.name
          };
          // accountList.value.forEach((item2) => {
          // props.advertiserId
          // });
        });
       
        emit('anchorMaterialListData', newAnchorMaterialList);
      }

      let promotion = {
        linkSource: linkSource.value,
        accountId: appStore.accountId, //管家账号id
        advertiserId: accountList.value[0].id, //广告主id
        projectId: null, // 项目id
        name: form.value.name, // 广告名称
        budget: form.value.budget, // 预算
        cpaBid: form.value.cpaBid, // 预算类型
        promotionMaterials: {
          callToActionButtons: form.value.callToActionButtons,
          productInfo: {
            titles: [form.value.titles],
            imageIds:
              imgType.value === 'online'
                ? form.value.imageIds
                : uploadFile.value.map((item) => {
                    return item.id;
                  }),
            imageType: imgType.value,
            selectedRows: imgType.value === 'online' ? selectedRows.value : uploadFile.value,
            sellingPoints: form.value.sellingPoints
          },
          miniProgramInfo: {
            appId: props.advertiserId[0].appId || null,
            startPath: form.value.startPath || null,
            params: form.value.params || null
          }
        },
        nativeSetting: {
          awemeId: form.value.awemeId,
          awemeName: form.value.awemeName,
          anchorRelatedType: 'AUTO' //原生锚点启用开关，允许值:不启用 OFF（默认值），自动生成 AUTO，手动选择 SELECT
        },
        source: form.value.source, //来源
        isCommentDisable: form.value.isCommentDisable, //广告评论,
        operation: form.value.operation,
        wechat: anchorPointList.value.map((item) => {
          return {
            anchorId: item.anchorId,
            anchorName: item.anchorName
          };
        })
      };
      // if (linkSource.value === '1') {
      //   promotion.urls = form.value.urls;
      // } else {
      //   promotion.urls = [
      //     {
      //       url: null,
      //       advertiserId: props.advertiserId[0].id,
      //       appId: props.advertiserId[0].appId || null,
      //       startPath: form.value.startPath || null,
      //       params: form.value.params || null
      //     }
      //   ];
      // }
      emit('strategyUrls', accountDataLists.value);
      let newAccountDataLists = JSON.parse(JSON.stringify(accountDataLists.value));
      promotion.urls = newAccountDataLists.map((item) => {
        if (item.linkSource == '1') {
          return {
            advertiserId: item.id,
            appId: item.appId || null,
            url: item.linkUrl
          };
        } else {
          return {
            advertiserId: item.id,
            appId: item.appId || null,
            startPath: item.startPath || null,
            params: item.params || null
          };
        }
      });
      emit('update:drawerAbs', false);
      emit('selectedRows', promotion);

      // emit('urls', form.value.urls);
    }
  });
};
// 选择链接
const handleLink = (accountItm, accountIdx) => {
  // 循环账户id，进行拼接list，根据账户id进行push，最后赋值给urls
  accountList.value.map((item) => {
    if (item.id === form.value.selectAccountId) {
      item.linkId = accountItm.linkId;
      item.linkUrl = linkedList.value.find((item) => item.linkId === accountItm.linkId)?.link;
      item.linkName = linkedList.value.find((item) => item.linkId === accountItm.linkId)?.linkRemark;

      accountDataLists.value[accountIdx].linkId = item.linkId;
      accountDataLists.value[accountIdx].linkUrl = item.linkUrl;
      accountDataLists.value[accountIdx].linkName = item.linkName;
    }
  });

  if (accountItm.linkSource == '1') {
    accountLinkList.value = accountList.value.filter((item) => item.id == accountItm.id);
  }
  showLinkTable.value = true;
  // form.value.urls = accountLinkList.value.map((item) => {
  //   return { url: item.linkUrl, linkId: item.linkId, advertiserId: item.id, linkName: item.linkName };
  // });
};

// 清空
const emptiedCallToActionButton = () => {
  form.value.callToActionButtons = [];
};
const emptiedSellingPoints = () => {
  form.value.sellingPoints = [];
};
// 添加标签
const handleAddCallToActionButton = () => {
  if (!callToActionButtonsItem.value) {
    ElMessage({
      message: '请输入标签',
      type: 'warning'
    });
    return;
  }
  // 最多只能十条数据
  if (form.value.callToActionButtons.length > 10) {
    ElMessage({
      message: '最多添加10个标签',
      type: 'warning'
    });
    return;
  }
  if (callToActionButtonsItem.value.includes(' ')) {
    // 为空的要过滤掉
    const callToActionButtonsArr1 = callToActionButtonsItem.value.split(' ').filter((item) => item);
    const set = new Set(callToActionButtonsArr1);
    const callToActionButtonsArr = Array.from(set);
    if (callToActionButtonsArr.length < callToActionButtonsArr1.length) {
      ElMessage({
        message: '已过滤掉相同的值',
        type: 'warning'
      });
    }

    if (callToActionButtonsArr.length + form.value.callToActionButtons.length > 10) {
      ElMessage({
        message: '最多添加10个标签',
        type: 'warning'
      });
      return;
    }

    if (callToActionButtonsArr.some((item) => item.length < 2 || item.length > 6)) {
      ElMessage({
        message: '有标签不符合规则，每项请输入2-6个字符',
        type: 'warning'
      });
      return;
    }

    callToActionButtonsArr.forEach((item) => {
      // form.value.callToActionButtons.push({
      //   id: '',
      //   name: item,
      //   type: '3'
      // });
      form.value.callToActionButtons.push(item);
    });
  } else {
    if (callToActionButtonsItem.value.length < 2 || callToActionButtonsItem.value.length > 6) {
      ElMessage({
        message: '请输入2-6个字符',
        type: 'warning'
      });
      return;
    }

    form.value.callToActionButtons.push(callToActionButtonsItem.value);
  }
  return;
  callToActionButtonsItem.value = '';
};
// 删除标签
const handleDelCallToActionButton = (index: number) => {
  form.value.callToActionButtons.splice(index, 1);
};
// 获取链接列表
const handleQueryToolsAssetLinkList = async (advertiserId: any) => {
  // console.log('获取链接列表',props.advertiserId);
  let r = true;
  props.advertiserId.map((item) => {
    if (!r) return;
    if (!item.instanceId) {
      r = false;
    }
  });
  if (!r) {
    proxy?.$modal.msgError('请先在项目中选择小程序');
    return;
  }
  const curAccount = props.advertiserId.find((item) => item.id === advertiserId);
  linkedList.value = [];
  queryParams.value.instanceId = curAccount.instanceId;
  queryParams.value.advertiserId = advertiserId;
  const res = await queryToolsAssetLinkList(queryParams.value);
  linkedList.value = res.data.list;
};
const handleListNativeAnchor = async () => {
  const res = await listNativeAnchor(queryParams.value);
  anchorList.value = res.rows;
};
const getSelectedRows = (val: any) => {
  selectedRows.value = val;
  imgType.value = 'online';
  form.value.imageIds = val.map((item) => item.id);
  form.value.selectedRows = val;
  form.value.imgType = 'online';
  form.value.tempImage = val;
};

const delSellingPoints = (index: number) => {
  form.value.sellingPoints.splice(index, 1);
};
const handleChatterNumber = (val: any) => {
  form.value.awemeId = val;
  const awemeName = chatterNumberList.value.find((item) => item.awemeId === val)?.awemeName;
  form.value.awemeName = awemeName;
  accountList.value.map((item) => {
    item.awemeId = val;
    item.awemeName = awemeName;
  });
  showAccountTable.value = true;
};
// 获取绑定的抖音号
const handleGetIesAccountSearch = async (val: string) => {
  const { data: res } = await getIesAccountSearch(queryParams.value);
  chatterNumberList.value = res;
};
const updateIsMaterialLibrary = (val: boolean) => {
  isMaterialLibrary.value = val;
};
const addMaterialLibrary = (index) => {
  if (selectedRows.value.length > 10) {
    ElMessage({
      message: '最多添加10个素材',
      type: 'warning'
    });
    return;
  }
  isMaterialLibrary.value = true;
};

const delImg = (index: number) => {
  selectedRows.value.splice(index, 1);
  if (selectedRows.value.length <= 0) imgType.value = null;
};
const addSellingPoints = () => {
  if (!sellingPointsItem.value) {
    ElMessage({
      message: '请输入标签',
      type: 'warning'
    });
    return;
  }
  // 最多只能十条数据
  if (form.value.sellingPoints.length > 10) {
    ElMessage({
      message: '最多添加10个标签',
      type: 'warning'
    });
    return;
  }
  if (sellingPointsItem.value.includes(' ')) {
    // 为空的要过滤掉
    const sellingPointsArr1 = sellingPointsItem.value.split(' ').filter((item) => item);
    const set = new Set(sellingPointsArr1);
    const sellingPointsArr = Array.from(set);
    if (sellingPointsArr.length < sellingPointsArr1.length) {
      ElMessage({
        message: '已过滤掉相同的值',
        type: 'warning'
      });
    }
    if (sellingPointsArr.length + form.value.sellingPoints.length > 10) {
      ElMessage({
        message: '最多添加10个标签',
        type: 'warning'
      });
      return;
    }
    if (sellingPointsArr.some((item) => item.length < 6 || item.length > 9)) {
      ElMessage({
        message: '有标签不符合规则，每项请输入6-9个字符',
        type: 'warning'
      });
      return;
    }

    sellingPointsArr.forEach((item) => {
      form.value.sellingPoints.push(item);
    });
  } else {
    if (sellingPointsItem.value.length < 6 || sellingPointsItem.value.length > 9) {
      ElMessage({
        message: '请输入6-9个字符',
        type: 'warning'
      });
      return;
    }
    form.value.sellingPoints.push(sellingPointsItem.value);
  }
  sellingPointsItem.value = '';
};

const setUserList = () => {
  accountList.value = props.advertiserId.map((item) => {
    return {
      ...item,
      awemeId: form.value.awemeId || '',
      awemeName: form.value.awemeName || chatterNumberList.value.find((subitem) => subitem.awemeId === form.value.awemeId)?.awemeName || '',
      linkUrl: form.value.urls[0].url || '',
      linkName: form.value.urls[0].linkName || '',
      linkId: form.value.linkId || '',
      anchorId: props.anchorMaterialList ? props.anchorMaterialList[0]?.anchorId : undefined,
      anchorName: props.anchorMaterialList ? props.anchorMaterialList[0]?.anchorName : undefined
    };
  });
};

/**
 * 字节小程序链接初始化
 */
const initByteAppLink = () => {
  accountDataLists.value = props.advertiserId.map((item) => {
    if (props.promotionData?.urls && props.promotionData?.urls.length) {
      const subitem = props.promotionData?.urls.find((subitem) => subitem.advertiserId === item.id);
      return {
        ...item,
        linkUrl: subitem.url || '',
        linkName: subitem.linkName || '',
        linkId: subitem.linkId || '',
        startPath: subitem.startPath || '',
        params: subitem.params || '',
        appId: item.appId || '',
        linkSource: subitem.linkSource ? subitem.linkSource : subitem.startPath ? '2' : '1'
      };
    } else {
      return {
        ...item,
        linkUrl: '',
        linkName: '',
        linkId: '',
        startPath: '',
        params: '',
        linkSource: '1'
      };
    }
  });
};

watch(
  () => props.microPromotionType,
  () => {
    nextTick(() => {
      if (props.microPromotionType === 'BYTE_APP' && props.advertiserId) {
        initByteAppLink();
      }
    });
  },
  { immediate: true }
);
watch(
  () => form.value.awemeId,
  () => {
    if (form.value.awemeId) {
      nextTick(() => {
        handleChatterNumber(form.value.awemeId);
        setUserList();

        showAccountTable.value = true;
      });
    }
  }
);

watch(
  () => props.promotionData,
  () => {
    if (props.promotionData?.nativeSetting.awemeId) {
      linkSource.value = props.promotionData.linkSource || '1';
      form.value.awemeId = props.promotionData.nativeSetting.awemeId;
      form.value.awemeName = props.promotionData.nativeSetting.awemeName;
      form.value.budget = props.promotionData.budget;
      form.value.cpaBid = props.promotionData.cpaBid;
      form.value.source = props.promotionData.source;
      form.value.callToActionButtons = props.promotionData.promotionMaterials.callToActionButtons;
      form.value.imageIds = props.promotionData?.promotionMaterials?.productInfo?.imageIds;
      callToActionButtonsItem.value = form.value.callToActionButtons;
      form.value.sellingPoints = props.promotionData.promotionMaterials.productInfo.sellingPoints;
      sellingPointsItem.value = form.value.sellingPoints;
      form.value.operation = props.promotionData.operation;
      form.value.isCommentDisable = props.promotionData.isCommentDisable;
      imgType.value = null;
      //已选商品信息
      if (
        props.promotionData?.promotionMaterials?.productInfo?.selectedRows &&
        props.promotionData?.promotionMaterials?.productInfo?.selectedRows.length
      ) {
        imgType.value = props.promotionData?.promotionMaterials?.productInfo?.imageType;
      }
      if (props.microPromotionType === 'BYTE_APP') {
        initByteAppLink();
      }

      if (props.promotionData?.promotionMaterials?.productInfo?.imageType === 'online') {
        selectedRows.value = props.promotionData?.promotionMaterials?.productInfo.selectedRows;
        form.value.tempImage = selectedRows.value;
      } else {
        uploadFile.value = props.promotionData?.promotionMaterials?.productInfo.selectedRows;
        form.value.tempImage = uploadFile.value;
      }
      form.value.tempImage = props.promotionData?.promotionMaterials?.productInfo.selectedRows.map((item) => {
        return {
          url: item.url,
          filename: item.filename,
          size: item.size,
          id: item.id
        };
      });
    }
    selectAdvertiserId.value = props.advertiserId[0].id; //默认选中第一个账户
  },
  { immediate: true }
);
watch(
  () => props.urlsData,
  () => {
    nextTick(() => {
      // if (props.urlsData && props.urlsData[0].linkId) {
      //   form.value.urls = props.urlsData;
      //   form.value.linkId = props.urlsData[0].linkId;
      //   showLinkTable.value = true;
      // }
    });
  },
  { immediate: true }
);
watch(
  () => props.anchorMaterialList,
  () => {
    nextTick(() => {
      if (props.anchorMaterialList && props.anchorMaterialList[0]?.anchorId) {
        showAnchorTable.value = true;
      }
    });
  },
  { immediate: true }
);

watch(
  () => uploadFile.value,
  () => {
    if (uploadFile.value.length) {
      imgType.value = 'local';
    } else {
      imgType.value = null;
    }
    form.value.tempImage = uploadFile.value;
  },
  {
    deep: true
  }
);
watch(
  () => props.dramaName,
  () => {
    nextTick(() => {
      form.value.titles = props.dramaName;
    });
  }
);

const handleDrawerClose = (val: boolean) => {
  drawerAbs.value = val;
  emit('update:drawerAbs', val);
};
</script>

<style scoped lang="scss">
.el-popup-parent--hidden {
  .el-popper {
    :deep(.el-select-dropdown) {
      width: 400px !important;
    }
  }
}
.create-ads {
  .drawer-content {
    .drawer-content-item {
      .box-card {
        margin-bottom: 20px;
        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        :deep(.el-input) {
          width: 60% !important;
        }
        // :deep(.el-select .el-select__wrapper){
        //    width: 60% !important;
        // }

        .awemeId {
          :deep(.el-form-item__content) {
            display: block;
          }
        }
        .awemeId-desc {
          display: flex;
          flex-direction: column;
          margin-top: 10px;
          img {
            width: 516px;
            height: 85px;
            margin-bottom: 5px;
          }
          span {
            font-size: 12px;
            color: #999999;
          }
        }
        .call-to-action {
          :deep(.el-input-group__append) {
            cursor: pointer;
            color: #197afb;
            background: #d6eaff;
            padding: 0 10px;
            margin-right: 10px;
          }
        }
        .call-to-action-text {
          .tagged-added {
            border: 1px solid #dcdfe6;
            border-radius: 5px;
            width: 360px;
            height: 260px;
            .tagged-added-title {
              background: #f8f9fd;
              padding: 0 10px;
              display: flex;
              justify-content: space-between;
              align-items: center;
              height: 40px;
            }
            .tagged-added-content {
              padding: 10px;
              display: flex;
              flex-direction: column;
              // 允许换行
              flex-wrap: wrap;
              height: 220px;
              .tagged-added-content-item {
                span {
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  color: #409eff;
                  cursor: pointer;
                  box-sizing: border-box;
                  float: left;
                  height: 24px;
                  line-height: 24px;
                  padding-right: 8px;
                  padding-left: 9px;
                  margin-bottom: 8px;
                  color: #515a6e;
                  background-color: #f4f5fc;
                  border-radius: 4px;
                }
              }
            }
          }
        }
        .products-img {
          .products-img-box {
            display: flex;
            flex-wrap: wrap;

            .products-img-item {
              width: 100px;
              height: 100px;
              display: flex;
              align-items: center;
              justify-content: center;
              margin: 0 10px;
              position: relative;
              .el-icon {
                cursor: pointer;
                position: absolute;
                top: -10px;
                right: -10px;
                font-size: 15px;
              }
              img {
                width: 100px;
                height: 100px;
              }
            }
            .add-img {
              border: 1px dashed #d9d9d9;
              border-radius: 6px;
              cursor: pointer;
              background-color: #f5f7fa;
              width: 100px;
              height: 100px;
              display: flex;
              align-items: center;
              justify-content: center;
              margin: 0 10px;
              margin-bottom: 0px;
            }
          }
        }
      }
    }
  }
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
